<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option v-for="item in cateList" :key="item.index" :label="item.cate_name" :value="item.id" prop="item.cate_name" ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="sx" type="primary" size="small">筛选</el-button>
            <el-button @click="cz" type="info" size="small">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button @click="pubVisible=true" type="primary" size="small" class="btn-pub">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table
        border
        stripe
        :data="artList"
        style="width: 100%">
        <el-table-column prop="title" @click="yl(row.id)" label="文章标题">
          <template v-slot="{row}">
           <span @click="wzxq(row.id)">{{row.title}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="cate_name" label="文章分类">
        </el-table-column>
        <el-table-column label="发表时间">
          <template v-slot="{row}">
            {{formDate(row.pub_date)}}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态">
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button @click="del(row.id)" type="danger" size="mini">删除</el-button>
          </template>
        </el-table-column>
        </el-table>
      <!-- 分页区域 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="q.pagenum"
      :page-sizes="[2,3,5,10]"
      :page-size="q.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-card>
    <el-dialog @closed="dialogClosed" title="发表文章" :visible.sync="pubVisible" fullscreen width="30%" :before-close="handleClose">
      <el-form :model="pubForm" :rules="pubRules" ref="pubForm" label-width="100px" class="demo-pubForm">
        <el-form-item label="文章标题" prop="title">
          <el-input placeholder="请输入文章标题" v-model="pubForm.title"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select class="art-cate-sel" v-model="pubForm.cate_id" placeholder="请选择文章分类">
            <el-option v-for="item in cateList" :key="item.id" :value="item.id" :label="item.cate_name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <quill-editor @blur="$refs.pubForm.validateField('content')" v-model="pubForm.content"></quill-editor>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img">
          <!-- 用来显示封面的图片 -->
          <img v-if="cover" :src="cover" ref="imgRef" />
          <img v-else src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input @change="coverChange" type="file" style="display: none;" accept="image/*" ref="iptFile" />
          <!-- 选择封面的按钮 -->
          <el-button @click="$refs.iptFile.click()" type="text">+ 选择封面</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="pubArt('已发布')" type="primary">发布</el-button>
          <el-button @click="pubArt('草稿')" type="info">存入草稿</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 查看文章详情的对话框 -->
<el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
  <h1 class="title">{{wzxqList.title}}</h1>

  <div class="info">
    <span>作者：{{wzxqList.username||wzxqList.nickname}}</span>
    <span>发布时间：{{formDate(wzxqList.pub_date)}}</span>
    <span>所属分类：{{wzxqList.cate_name}}</span>
    <span>状态：{{wzxqList.state}}</span>
  </div>
  <!-- 分割线 -->
  <el-divider></el-divider>

  <img :src="'http://www.liulongbin.top:3008' + wzxqList.cover_img" alt="" />

  <div v-html="wzxqList.content"></div>
</el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
export default {
  name: 'ArtList',
  data () {
    return {
      // 查询参数对象
      pubVisible: false,
      detailVisible: false,
      cover: '',
      pic: '',
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: '',
        state: ''
      },
      cateList: [],
      pubRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [
          { required: true, message: '请选择文章标题', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文本内容', trigger: 'blur' }
        ],
        cover_img: [
          { required: true, message: '请上传封面', trigger: 'change' }
        ]
      },
      artList: [],
      total: 0,
      wzxqList: ''
    }
  },
  created () {
    this.getCateList()
    this.getArtList()
  },
  methods: {
    // 参数1: done 是一个函数, 调用它可以关闭 dialog
    handleClose (done) {
      // 参数1: 内容
      // 参数2: 标题
      // 参数3: 配置对象, 可以设置 type
      this.$confirm('此操作将导致文章信息丢失, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(_ => {
          // 用户点击了确定
          done()
        })
        // 用户点击了取消
        .catch(_ => {})
    },
    dialogClosed () {
      this.$refs.pubForm.resetFields()
      this.cover = ''
    },
    async getCateList () {
      const { data: res } = await this.$http.get('/my/cate/list')
      console.log(res)
      this.cateList = res.data
    },
    coverChange (e) {
      const file = e.target.files[0]
      if (file) {
        // const fr = new FileReader()
        // fr.readAsDataURL(file)
        // fr.onload = (e) => {
        //   this.cover = e.target.result
        // }
        this.cover = URL.createObjectURL(file)
        this.pubForm.cover_img = file
        this.$refs.pubForm.validateField('cover_img')
      } else {
        this.cover = ''
        this.pubForm.cover_img = ''
      }
    },
    pubArt (state) {
      this.pubForm.state = state
      this.$refs.pubForm.validate(async valid => {
        if (!valid) return
        const fd = new FormData()
        Object.keys(this.pubForm).forEach(item => fd.append(item, this.pubForm[item]))
        const { data: res } = await this.$http.post('/my/article/add', fd)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.getArtList()
        this.pubVisible = false
      })
    },
    async getArtList () {
      const { data: res } = await this.$http.get('/my/article/list', { params: this.q })
      console.log(res)
      this.artList = res.data
      this.total = res.total
    },
    formDate (date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.q.pagesize = val
      this.getArtList()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.q.pagenum = val
      this.getArtList()
    },
    del (id) {
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete('/my/article/info', { params: { id } })
          if (res.code !== 0) return this.$message.error(res.message)
          this.$message.success(res.message)
          console.log(this.artList)
          if (this.artList.length === 1 && this.q.pagenum > 1) {
            this.q.pagenum--
          }
          this.getArtList()
        }).catch(() => {
        })
    },
    sx () {
      this.getArtList()
    },
    cz () {
      this.q.cate_id = ''
      this.q.state = ''
      this.getArtList()
    },
    async wzxq (id) {
      const { data: res } = await this.$http.get('/my/article/info', { params: { id } })
      console.log(res)
      this.wzxqList = res.data
      this.detailVisible = true
      // this.pic = URL.createObjectURL(this.wzxqList.cover_img)
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
.art-cate-sel.el-select {
  width: 100%
}
/deep/ .quill-editor .ql-editor {
  height: 300px
}
</style>
